<template>
  <view class="address-edit-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <uni-icons type="left" size="24" color="#333"></uni-icons>
      </view>
      <text class="title">{{isEdit ? '编辑地址' : '新增地址'}}</text>
      <view class="header-actions">
        <text class="delete-btn" @click="deleteAddress" v-if="isEdit">删除</text>
        <text class="save-btn-header" @click="saveAddress" :class="{disabled: loading}">{{loading ? '保存中...' : '保存'}}</text>
      </view>
    </view>
    
    <!-- 表单 -->
    <view class="form-container">
      <view class="form-item" :class="{'error': !addressForm.name}">
        <text class="label">收货人</text>
        <input type="text" v-model="addressForm.name" placeholder="请输入收货人姓名" />
        <!-- <text class="error-msg" v-if="!addressForm.name">请输入收货人姓名</text> -->
      </view>
      
      <view class="form-item" :class="{'error': !validatePhone()}">
        <text class="label">手机号码</text>
        <input type="number" v-model="addressForm.phone" placeholder="请输入手机号码" maxlength="11" />
        <!-- <text class="error-msg" v-if="!validatePhone()">请输入手机号码</text> -->
      </view>
      
      <view class="form-item" :class="{'error': !addressForm.city}">
        <text class="label">所在城市</text>
        <!-- 新增包裹元素 -->
        <view class="custom-picker">
          <picker mode="selector" :range="cities" @change="cityChange" :value="cityIndex">
            <view class="picker-text">
              {{ addressForm.city || '请选择城市' }}
            </view>
          </picker>
          <!-- 新增下拉箭头图标 -->
          <uni-icons type="arrowdown" size="20" color="#666"></uni-icons>
        </view>
        <!-- <text class="error-msg" v-if="!addressForm.city">请选择所在城市</text> -->
      </view>
      
      <view class="form-item" :class="{'error': !addressForm.department}">
        <text class="label">小区/大厦/学校</text>
        <input type="text" v-model="addressForm.department" placeholder="请输入小区/大厦/学校" />
        <!-- <text class="error-msg" v-if="!addressForm.department">请输入小区/大厦/学校</text> -->
      </view>
      
      <view class="form-item" :class="{'error': !addressForm.houseNumber}">
        <text class="label">详细地址</text>
        <input type="text" v-model="addressForm.houseNumber" placeholder="请输入详细地址，如门牌号等" />
        <!-- <text class="error-msg" v-if="!addressForm.houseNumber">请输入详细地址</text> -->
      </view>
      
      <view class="form-item switch-item">
        <text class="label">设为默认地址</text>
        <switch :checked="addressForm.isDefault" @change="switchChange" color="#0086ff" />
      </view>
    </view>
    
    <!-- 底部保存按钮（仅新增时显示） -->
    <view class="save-btn" @click="saveAddress" v-if="!isEdit" :class="{disabled: loading}">
      <text>{{loading ? '保存中...' : '保存'}}</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      addressId: '',
      isEdit: false,
      loading: false,
      cities: ['北京', '上海', '杭州', '深圳', '郑州', '南京'],
      cityIndex: -1,
      addressForm: {
        name: '',
        phone: '',
        city: '',
        department: '',
        houseNumber: '',
        isDefault: false
      }
    }
  },
  onLoad(options) {
    if (options.id) {
      this.addressId = options.id;
      this.isEdit = true;
      this.loadAddressDetail();
    }
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    
    validatePhone() {
      if (!this.addressForm.phone) return false;
      return /^1\d{10}$/.test(this.addressForm.phone);
    },
    
    cityChange(e) {
      this.cityIndex = e.detail.value;
      this.addressForm.city = this.cities[this.cityIndex];
    },
    
    async loadAddressDetail() {
      try {
        const res = await this.getAddressList();
        if (res.statusCode === 200) {
          const address = res.data.find(item => item._id === this.addressId);
          if (address) {
            this.addressForm = {
              name: address.name,
              phone: address.phone,
              city: address.city,
              department: address.department,
              houseNumber: address.houseNumber,
              isDefault: address.isDefault || false
            };
            
            // 初始化选中的城市索引
            if (address.city) {
              this.cityIndex = this.cities.indexOf(address.city);
            }
          }
        }
      } catch (err) {
        console.error('获取地址详情失败:', err);
        uni.showToast({
          title: '获取地址详情失败',
          icon: 'none'
        });
      }
    },
    
    switchChange(e) {
      this.addressForm.isDefault = e.detail.value;
    },
    
    async saveAddress() {
      if (this.loading) return;
      
      // 表单验证
      if (!this.addressForm.name) {
        return uni.showToast({ title: '请输入收货人姓名', icon: 'none' });
      }
      
      if (!this.validatePhone()) {
        return uni.showToast({ title: '请输入手机号码', icon: 'none' });
      }
      
      if (!this.addressForm.city) {
        return uni.showToast({ title: '请选择所在城市', icon: 'none' });
      }
      
      if (!this.addressForm.department) {
        return uni.showToast({ title: '请输入小区/大厦/学校', icon: 'none' });
      }
      
      if (!this.addressForm.houseNumber) {
        return uni.showToast({ title: '请输入详细地址', icon: 'none' });
      }
      
      this.loading = true;
      uni.showLoading({ title: '保存中...', mask: true });
      
      try {
        const addressData = {
          name: this.addressForm.name,
          phone: this.addressForm.phone,
          city: this.addressForm.city,
          department: this.addressForm.department,
          houseNumber: this.addressForm.houseNumber,
          isDefault: this.addressForm.isDefault,
          address: `${this.addressForm.city} ${this.addressForm.department} ${this.addressForm.houseNumber}`
        };
        
        const res = await this.getAddressList();
        let addressList = res.data || [];
        
        if (this.isEdit) {
          // 编辑模式
          addressData._id = this.addressId;
          addressList = addressList.map(item => {
            if (item._id === this.addressId) return addressData;
            return addressData.isDefault ? {...item, isDefault: false} : item;
          });
        } else {
          // 新增模式
          addressData._id = 'address_' + Date.now();
          if (addressData.isDefault) {
            addressList = addressList.map(item => ({...item, isDefault: false}));
          }
          addressList.push(addressData);
        }
        
        await this.saveAddressList(addressList);
        
        uni.hideLoading();
        uni.showToast({
          title: this.isEdit ? '修改成功' : '添加成功',
          icon: 'success',
          success: () => {
            setTimeout(() => {
              uni.$emit('addressUpdate');
              uni.navigateBack();
            }, 1500);
          }
        });
      } catch (error) {
        console.error('保存失败:', error);
        uni.hideLoading();
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    async deleteAddress() {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个地址吗？',
        success: async (res) => {
          if (res.confirm) {
            uni.showLoading({ title: '删除中...', mask: true });
            try {
              const res = await this.getAddressList();
              const addressList = res.data.filter(item => item._id !== this.addressId);
              await this.saveAddressList(addressList);
              
              uni.hideLoading();
              uni.showToast({ title: '删除成功' });
              uni.$emit('addressUpdate');
              setTimeout(() => uni.navigateBack(), 1000);
            } catch (error) {
              console.error('删除失败:', error);
              uni.hideLoading();
              uni.showToast({ title: '删除失败', icon: 'none' });
            }
          }
        }
      });
    },
    
    getAddressList() {
      return new Promise((resolve, reject) => {
        uni.request({
          url: 'http://localhost:3000/address',
          success: resolve,
          fail: reject
        });
      });
    },
    
    saveAddressList(list) {
      return new Promise((resolve, reject) => {
        uni.setStorage({
          key: 'addressList',
          data: JSON.stringify(list),
          success: resolve,
          fail: reject
        });
      });
    }
  }
}
</script>

<style lang="scss">
.address-edit-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.header {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #fff;
  position: relative;
  
  .back-btn {
    margin-right: 20rpx;
  }
  
  .title {
    flex: 1;
    text-align: center;
    font-size: 32rpx;
    font-weight: bold;
  }
  
  .header-actions {
    display: flex;
    align-items: center;
    
    .delete-btn {
      color: #ff4d4f;
      font-size: 28rpx;
      margin-right: 30rpx;
    }
    
    .save-btn-header {
      color: #0086ff;
      font-size: 28rpx;
      
      &.disabled {
        color: #ccc;
      }
    }
  }
}

.form-container {
  background-color: #fff;
  margin-top: 20rpx;
  
  .form-item {
    display: flex;
    flex-direction: column;
    padding: 30rpx 20rpx;
    border-bottom: 1rpx solid #f5f5f5;
    
    .label {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 20rpx;
    }
    
    input {
      font-size: 28rpx;
      height: 50rpx;
    }
    
    .picker-text {
      font-size: 28rpx;
      color: #333;
      padding: 10rpx 0;
      
      &:empty::after {
        content: '请选择城市';
        color: #999;
      }
    }
    
    &.switch-item {
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
    }
    
    &.error {
      border-bottom-color: #0f0e0e;
      
      input, .picker-text {
        color: #161414;
      }
    }
    
    .error-msg {
      color: #141111;
      font-size: 24rpx;
      margin-top: 10rpx;
    }

    /* 新增自定义下拉框样式 */
    .custom-picker {
      display: flex;
      align-items: center;
      position: relative;
      border: 1rpx solid #ccc;
      border-radius: 8rpx;
      padding: 10rpx 20rpx;
      background-color: #fff;
      transition: border-color 0.3s ease;

      &:hover {
        border-color: #0086ff;
      }

      uni-icons {
        position: absolute;
        right: 20rpx;
        top: 50%;
        transform: translateY(-50%);
      }
    }
  }
}

.save-btn {
  position: fixed;
  bottom: 30rpx;
  left: 30rpx;
  right: 30rpx;
  background-color: #0086ff;
  color: #fff;
  text-align: center;
  padding: 20rpx 0;
  border-radius: 40rpx;
  font-size: 30rpx;
  
  &:active {
    opacity: 0.8;
  }
  
  &.disabled {
    background-color: #ccc;
  }
}
</style>